package com.example.pro1.controller.zhao;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pro1.entity.lian.Address;
import com.example.pro1.entity.zhao.Logistics;
import com.example.pro1.entity.zhao.LogisticsTrace;
import com.example.pro1.entity.zhao.OrderInfo;
import com.example.pro1.enums.logistics.LogisticsS;
import com.example.pro1.mapper.lian.AddressMapper;
import com.example.pro1.mapper.zhao.LogisticsMapper;
import com.example.pro1.mapper.zhao.LogisticsTraceMapper;
import com.example.pro1.service.lian.AddressService;
import com.example.pro1.service.zhao.kdniao.KdniaoService;
import com.example.pro1.service.zhao.table.LogisticsService;
import com.example.pro1.service.zhao.table.LogisticsTraceService;
import com.example.pro1.util.zhao.HttpUtils;
import com.example.pro1.util.zhao.KV2MapUtils;
import com.example.pro1.valu.R;
import com.example.pro1.valu.Standard;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin//开放前端跨域访问
@Api(tags = "物流查看")
@RestController
@RequestMapping("/api/logistcs")
@Slf4j
public class KdNiaoController {



    @Resource
    private KdniaoService kdniaoService;
    @Resource
    private LogisticsService logisticsService;

    @Resource
    private AddressMapper addressService;
    @Resource
    private  LogisticsMapper logisticsMapper;
    @Resource
    private LogisticsTraceMapper logisticsTraceServiceMapepr;

    @ApiOperation("地址查询")
    @GetMapping("/dizhi/{addressId}")
    public  Standard zhaodizhi(@PathVariable String addressId)
    {
        QueryWrapper<Address> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("addressId",addressId);
        Address address = addressService.selectOne(objectQueryWrapper);

        return  R.ok().data("Address",address);
    }
    @ApiOperation("物流信息查询")
    @GetMapping("/wuliuxin/{doerno}")
    public  Standard wuliuxinxi(@PathVariable String doerno)
    {
        QueryWrapper<Logistics> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("orderId",doerno);
        Logistics logistics = logisticsMapper.selectOne(objectQueryWrapper);
        QueryWrapper<LogisticsTrace> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("logistic_code",logistics.getLogisticCode());
        List<LogisticsTrace> logisticsTraces = logisticsTraceServiceMapepr.selectList(queryWrapper);
        return  R.ok().data("list",logisticsTraces);
    }
    //物流追踪订阅接口
    @PostMapping("/subcription/{shipperCode}/{LogisticCode}/{doerno}")
    public Standard subscription(@PathVariable String shipperCode,@PathVariable String LogisticCode,@PathVariable String doerno ) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("shipperCode",shipperCode);
        map.put("LogisticCode",LogisticCode);
        map.put("doerno",doerno);
        if(kdniaoService.sendPost(map)==1)
            return R.ok();
        else
            return R.nonono();
    }
    @PostMapping("/test")
    public  String setKdniaoService(HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws UnsupportedEncodingException {
        String x=HttpUtils.readData(httpRequest);

        System.out.println("dasdsadsadsa");
        Map<String,String> entity=KV2MapUtils.String2Map(x);
        String request= URLDecoder.decode(entity.get("RequestData"), "utf-8");//解码

        Gson gson = new Gson();
        JSONObject jasonObject = JSONObject.fromObject(request);
        Map requestData = (Map)jasonObject;

        int count=Integer.parseInt(requestData.get("Count").toString());//订单数量
         List<HashMap<String,Object>> Data= ( List<HashMap<String, Object>>) requestData.get("Data");

        for(int i=0;i<count;i++)
        {
            Logistics logistics = new Logistics();
            //TODO???可能存在编码问题。若有则用Gson变换数据结构
            JSONObject jasonObject1 = JSONObject.fromObject(Data.get(i));
            Map daa = (Map)jasonObject1;
            String LogisticCode= (String) daa.get("LogisticCode");//物流单号
                /*普通物流状态：0-暂无轨迹信息1-已揽收2-在途中3-签收4-问题件*/
            int State= Integer.parseInt(daa.get("State").toString()) ;//订单状态
            logistics.setLogisticCode(LogisticCode);
            logistics.setStatus(LogisticsS.get(State));
            logisticsService.updateById(logistics);

            List<HashMap<String,String>> Traces= (List<HashMap<String, String>>) daa.get("Traces");
            for (int k=0;k<Traces.size();k++)
            {
                JSONObject jasonObject2 = JSONObject.fromObject(Traces.get(k));
                Map Trace = (Map)jasonObject2;

                String AcceptTime= (String) Trace.get("AcceptTime");
                String AcceptStation=(String) Trace.get("AcceptStation");
                String Remark=(String) Trace.get("Remark");
                LogisticsTrace logisticsTrace = new LogisticsTrace();
                logisticsTrace.setLogisticCode(LogisticCode);
                logisticsTrace.setAcceptStation(AcceptStation);
                logisticsTrace.setAcceptTime(AcceptTime);
                logisticsTrace.setRemark(Remark);
                QueryWrapper<LogisticsTrace> eq = new QueryWrapper<>();
                eq.eq("logistic_code", LogisticCode).eq("Accept_station", AcceptStation).eq("Accept_time", AcceptTime);
                if(logisticsTraceServiceMapepr.selectOne(eq)==null)
                    logisticsTraceServiceMapepr.insert(logisticsTrace);//插入一条新的轨迹
            }
        }



        return "{\n" +
                "        \"EBusinessID\": \"1151847\",\n" +
                "        \"UpdateTime\": \"2016-08-09 16:42:38\",\n" +
                "        \"Success\": true,\n" +
                "        \"Reason\": \"\"\n" +
                "        }";

    }

    @PostMapping("/getsub")
    public void getsub(HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException {

        log.info("dasdas");
        String entity=HttpUtils.readData(httpRequest);

        PrintWriter writer=null;
        try {
            httpResponse.setStatus(200);


            writer = httpResponse.getWriter();
            writer.println(kdniaoService.creatSysR());
        } finally {
            writer.close();
        }

        /*if(returnmap.get("RequestType").toString().equals("101"))//订阅物流信息推送
        {
           HashMap<String,Object> requestData= (HashMap<String, Object>) returnmap.get("RequestData");
            int count=Integer.parseInt(requestData.get("Count").toString());//订单数量
            HashMap<String, List<HashMap<String,Object>>> data= (HashMap<String, List<HashMap<String, Object>>>) requestData.get("Data");
            List<HashMap<String,Object>> Data=data.get("Data");
            for(int i=0;i<count;i++)
            {
                Logistics logistics = new Logistics();
                //TODO???可能存在编码问题。若有则用Gson变换数据结构
                HashMap<String,Object> daa=Data.get(i);
                String LogisticCode= (String) daa.get("LogisticCode");//物流单号
                *//*普通物流状态：0-暂无轨迹信息1-已揽收2-在途中3-签收4-问题件*//*
                int State= Integer.parseInt(daa.get("State").toString()) ;//订单状态
                logistics.setLogisticCode(LogisticCode);
                logistics.setStatus(LogisticsS.get(State));
                logisticsService.updateById(logistics);

                List<HashMap<String,String>> Traces= (List<HashMap<String, String>>) daa.get("Traces");
                for (int k=0;k<Traces.size();k++)
                {
                    HashMap<String,String> Trace=Traces.get(k);
                    String AcceptTime=Trace.get("AcceptTime");
                    String AcceptStation=Trace.get("AcceptStation");
                    String Remark=Trace.get("Remark");
                    LogisticsTrace logisticsTrace = new LogisticsTrace();
                    logisticsTrace.setLogisticCode(LogisticCode);
                    logisticsTrace.setAcceptStation(AcceptStation);
                    logisticsTrace.setAcceptTime(AcceptTime);
                    logisticsTrace.setRemark(Remark);
                    logisticsTraceServiceMapepr.insert(logisticsTrace);//插入一条新的轨迹
                }
            }

        }*/


    }
}
